document.addEventListener('DOMContentLoaded', () => {
  const dropZone = document.getElementById('dropZone');
  const fileInput = document.getElementById('fileInput');
  const qualityInput = document.getElementById('quality');
  const qualityValue = document.getElementById('qualityValue');
  const maxWidthInput = document.getElementById('maxWidth');
  const compressBtn = document.getElementById('compressBtn');
  const downloadLink = document.getElementById('downloadLink');
  const originalCanvas = document.getElementById('originalCanvas');
  const compressedCanvas = document.getElementById('compressedCanvas');

  // 更新质量显示
  qualityInput.addEventListener('input', () => {
    qualityValue.textContent = `${Math.round(qualityInput.value * 100)}%`;
  });

  // 处理文件选择
  const handleFile = (file) => {
    if (!file.type.startsWith('image/')) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      const img = new Image();
      img.onload = () => {
        // 显示原始图片
        drawImageToCanvas(img, originalCanvas);
        compressBtn.disabled = false;
      };
      img.src = e.target.result;
    };
    reader.readAsDataURL(file);
  };

  // 拖放事件处理
  dropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropZone.classList.add('dragover');
  });

  dropZone.addEventListener('dragleave', () => {
    dropZone.classList.remove('dragover');
  });

  dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropZone.classList.remove('dragover');
    const file = e.dataTransfer.files[0];
    handleFile(file);
  });

  // 文件选择事件
  fileInput.addEventListener('change', () => {
    const file = fileInput.files[0];
    handleFile(file);
  });

  // 压缩按钮点击事件
  compressBtn.addEventListener('click', () => {
    const img = originalCanvas.getContext('2d').getImageData(0, 0, originalCanvas.width, originalCanvas.height);
    const maxWidth = parseInt(maxWidthInput.value) || 1920;
    const quality = parseFloat(qualityInput.value) || 0.8;

    // 调整尺寸
    const scale = Math.min(1, maxWidth / img.width);
    const newWidth = img.width * scale;
    const newHeight = img.height * scale;

    compressedCanvas.width = newWidth;
    compressedCanvas.height = newHeight;
    const ctx = compressedCanvas.getContext('2d');
    ctx.drawImage(originalCanvas, 0, 0, newWidth, newHeight);

    // 生成压缩文件
    compressedCanvas.toBlob((blob) => {
      const url = URL.createObjectURL(blob);
      downloadLink.href = url;
      downloadLink.download = `compressed_${Date.now()}.jpg`;
      downloadLink.style.display = 'inline-block';
    }, 'image/jpeg', quality);
  });

  // 工具函数：绘制图片到画布
  function drawImageToCanvas(img, canvas) {
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);
  }
});